from boot import Union, QWidget, CurrentSelectedID, QFileDialog, IMG_ROOT_DIR, os, logger, QLineEdit
from view.widget.qq9_page_base import QQ9PageBase
from view.com.cust_list_frame import CustomerListFrame
from view.com.cust_content_frame import CustomerContentFrame
from view.widget.qq9_messagebox import QQ9MessageBoxWidget, QQ9MessageBox, QQ9TipsMessageWidget
from view.widget.qq9_label import QQ9FromTitle
from view.widget.qq9_line_edit import QQ9LineEdit, QQ9NumberLineEdit
from db.db_customer import DBCustomer
from utils.file import *
from utils.id import generate_id, random_account
from view.pages.utils.map import cust_content_dict_map
from view.pages.utils.message_box import message_box
from view.pages.utils.db_d import db_cust_wrapper
import hashlib


__all__ = ["PageCustomers"]


SHOW_BACK_NAME: bool = False
DELETE_RESULT: str = ""


class PageCustomers(QQ9PageBase):

    def __init__(self,
                 parent: Union[QWidget, None] = None,
                 ):
        super().__init__(parent)

        # 创建客户列表框架
        self.cust_list_frame = CustomerListFrame()
        self.main_h_layout.addWidget(self.cust_list_frame)

        # 客户内容框架
        self.cust_content_frame = CustomerContentFrame()
        self.main_h_layout.addWidget(self.cust_content_frame)

        # 初始化步骤
        # 1.刷新列表内容
        self.show_list_widget()
        # 2.绑定list_widget的点击事件(选择改变)
        self.cust_list_frame.list_widget.itemSelectionChanged.connect(self.show_content_widget)
        # 3.绑定更换头像信号
        self.cust_content_frame.avatar_info_widget.sgn_avatar_changed.connect(self.set_avatar_icon)
        # 4.绑定编辑按钮
        self.cust_content_frame.edit_button.sgn_clicked.connect(self.set_cust_info)
        # 5.绑定新建按钮
        self.cust_list_frame.search_list_frame.add_button.sgn_clicked.connect(self.add_cust_info)
        # 6.绑定删除按钮
        self.cust_content_frame.delete_button.sgn_clicked.connect(self.delete_cust_info)

    @cust_content_dict_map
    def show_list_widget(self, new_dict_list=None):
        # 刷新列表
        self.cust_list_frame.list_widget.refresh_list_widget(new_dict_list, show_back_name=SHOW_BACK_NAME)

    @cust_content_dict_map
    def edit_list_widget(self, new_dict_list=None):
        # 编辑之后刷新列表
        self.cust_list_frame.list_widget.edit_list_widget(new_dict_list, show_back_name=SHOW_BACK_NAME)

    @cust_content_dict_map
    def delete_list_widget(self, new_dict_list=None):
        # 删除之后刷新列表
        self.cust_list_frame.list_widget.delete_list_widget(new_dict_list, show_back_name=SHOW_BACK_NAME)

    @cust_content_dict_map
    def add_list_widget(self, new_dict_list=None):
        # 添加之后刷新列表
        self.cust_list_frame.list_widget.add_list_widget(new_dict_list, show_back_name=SHOW_BACK_NAME)

    @db_cust_wrapper
    def show_content_widget(self, cust_db:DBCustomer=None):
        # 刷新内容
        try:
            info_dict = cust_db.get_info(CurrentSelectedID.customer_selected_id)

            self.cust_content_frame.set_info(
                cust_id=info_dict["cust_id"],
                cust_name=info_dict["cust_name"],
                cust_tel=info_dict["cust_tel"],
                cust_company=info_dict["cust_company"],
                cust_icon=info_dict["cust_icon"]
            )

            self.cust_content_frame.set_yes_content()
        except TypeError:
            logger.warning("由于删除了项目，本地获取item_id时不存在")

    @db_cust_wrapper
    def set_avatar_icon(self, cust_db:DBCustomer=None):
        # 设置头像图片
        # 1.打开对话框
        file_dialog = QFileDialog()
        file_dialog.setWindowTitle("选择头像")
        file_dialog.setNameFilter("Images (*.png *.jpg *.jpeg *.bmp *.gif)")
        file_dialog.setFileMode(QFileDialog.ExistingFile)

        # 2.选择图片
        if file_dialog.exec_():
            selected_files = file_dialog.selectedFiles()
            if selected_files:
                # 3.获取选择的图片路径
                file_path = selected_files[0]
                # 4.复制图片到指定目录
                copy_file(file_path, dst_dir := IMG_ROOT_DIR + "/avatar/")
                # 5.写入数据库
                cust_db.update_icon(cust_icon=dst_dir + os.path.basename(file_path),
                                    cust_id=CurrentSelectedID.customer_selected_id)
                # 6.刷新列表
                self.edit_list_widget()

    @message_box(title="编辑客户信息")
    @db_cust_wrapper
    def set_cust_info(self, w: QQ9MessageBox=None, cust_db:DBCustomer=None):
        # 编辑客户信息
        c = CustomerEditFrame(parent=w, add=False)
        if w.exec():
            # 2.获取当前值
            cust_name = c.name_edit.text()

            # 判断名字合法性顶
            if cust_name.replace(" ", "") == "":
                return
            if cust_name == "全部":
                cust_name = cust_name + CurrentSelectedID.customer_selected_id
            else:
                cust_info_dict = cust_db.get_all_info()
                for item in cust_info_dict:
                    if cust_name == item["cust_name"] and item["cust_id"] != CurrentSelectedID.customer_selected_id:
                        return

            cust_tel = c.tel_edit.text()
            cust_company = c.company_edit.text()
            # 3.写入数据库
            cust_db.update_personal_info(
                cust_name=cust_name,
                cust_tel=cust_tel,
                cust_company=cust_company,
                cust_id=CurrentSelectedID.customer_selected_id,
            )
            # 4.刷新列表
            self.edit_list_widget()

    @message_box(title="新建客户信息")
    @db_cust_wrapper
    def add_cust_info(self, w: QQ9MessageBox=None, cust_db:DBCustomer=None):
        # 新建客户信息
        c = CustomerEditFrame(parent=w, add=True)
        cust_id = random_account()

        if w.exec():
            # 2.获取当前值
            cust_name = c.name_edit.text()

            # 判断名字合法性顶
            if cust_name.replace(" ", "") == "":
                return
            cust_info_dict = cust_db.get_all_info()
            if cust_name == "全部":
                cust_name = cust_name + cust_id
            else:
                for item in cust_info_dict:
                    if cust_name == item["cust_name"]:
                        cust_name = cust_name + cust_id
                        break

            cust_tel = c.tel_edit.text()
            cust_company = c.company_edit.text()
            cust_icon = IMG_ROOT_DIR + "/avatar/默认.jpg"
            cust_db.add_info(
                cust_id=cust_id,
                cust_name=cust_name,
                cust_tel=cust_tel,
                cust_company=cust_company,
                cust_icon=cust_icon
            )
            # 4.更改当前选中ID
            CurrentSelectedID.customer_selected_id = cust_id
            # 4.刷新列表
            self.add_list_widget()

    @message_box(title="删除客户信息", width=300, height=150)
    @db_cust_wrapper
    def delete_cust_info(self, w: QQ9MessageBox=None, cust_db:DBCustomer=None):
        # 删除客户信息
        QQ9TipsMessageWidget(parent=w, text="确定删除此客户吗？")
        if w.exec():
            # 1.删除客户信息密码确认
            self.delete_cust_info_configuration()


    @message_box(title="删除客户信息密码确认", width=400, height=150)
    @db_cust_wrapper
    def delete_cust_info_configuration(self, w: QQ9MessageBox=None, cust_db:DBCustomer=None):
        # 删除客户信息密码确认
        global DELETE_RESULT
        c = PasswordEditFrame(parent=w)
        if w.exec():
            # 哈希256加密密码
            hash_object = hashlib.sha256(c.password_edit.text().encode())
            hex_dig = hash_object.hexdigest()
            if hex_dig == "c67ea1a7c60a833a8b56a9e2b99d8e4803b4d3dcb7dc5982313a51ab264ee15b":
                # 1. 在数据库中删除
                cust_db.delete_info(CurrentSelectedID.customer_selected_id)
                # 2.切换成LOGO
                self.cust_content_frame.set_no_content()
                # 3.刷新列表
                self.delete_list_widget()
                # 4.结果提醒
                DELETE_RESULT = "删除成功"
            else:
                DELETE_RESULT = "密码错误，删除失败"
            self.delete_finish_tips()


    @message_box(title="删除结果", width=300, height=150)
    def delete_finish_tips(self, w: QQ9MessageBox=None):
        # 删除结果信息
        global DELETE_RESULT
        QQ9TipsMessageWidget(parent=w, text=DELETE_RESULT)
        if w.exec():
            pass


class CustomerEditFrame(QQ9MessageBoxWidget):

    def __init__(self,
                 parent: Union[QWidget, None] = None,
                 add: bool = False
                 ):
        super().__init__(parent, add)

        # 标题
        self.name_label = QQ9FromTitle(text="客户姓名")

        # 标题
        self.tel_label = QQ9FromTitle(text="手机号码")

        # 标题
        self.company_label = QQ9FromTitle(text="公司名称")

        self.name_edit = QQ9LineEdit()
        self.tel_edit = QQ9NumberLineEdit()
        self.company_edit = QQ9LineEdit()

        self.main_g_layout.addWidget(self.name_label, 0, 0)
        self.main_g_layout.addWidget(self.name_edit, 0, 1)
        self.main_g_layout.addWidget(self.tel_label, 1, 0)
        self.main_g_layout.addWidget(self.tel_edit, 1, 1)
        self.main_g_layout.addWidget(self.company_label, 2, 0)
        self.main_g_layout.addWidget(self.company_edit, 2, 1)

        if not add:
            self.set_info()

    @db_cust_wrapper
    def set_info(self, cust_db:DBCustomer=None):
        info_dict = cust_db.get_info(CurrentSelectedID.customer_selected_id)
        self.name_edit.setText(info_dict["cust_name"])
        self.tel_edit.setText(info_dict["cust_tel"])
        self.company_edit.setText(info_dict["cust_company"])


class PasswordEditFrame(QQ9MessageBoxWidget):

    def __init__(self,
                 parent: Union[QWidget, None] = None,
                 ):
        super().__init__(parent)

        # 标题
        self.name_label = QQ9FromTitle(text="删除密码")

        # 密码框
        self.password_edit = QQ9LineEdit()
        self.password_edit.setEchoMode(QLineEdit.Password)

        self.main_g_layout.addWidget(self.name_label, 0, 0)
        self.main_g_layout.addWidget(self.password_edit, 0, 1)
